package com.yang.gateway.util;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.yang.common.core.result.R;
import org.yang.common.i18n.enums.RI18nEnum;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;


/**
 * WebFlux 响应处理器
 * @Author: Islands
 * @create: 2024-03-29 17:27
 */
@Slf4j
public class WebFluxUtils {

    public static Mono<Void> writeErrorResponse(ServerHttpResponse response, RI18nEnum ri18nEnum) {
        HttpStatus status = determineHttpStatus(ri18nEnum);
        response.setStatusCode(status);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.getHeaders().setAccessControlAllowOrigin("*");
        response.getHeaders().setCacheControl("no-cache");

        String responseBody = JSONUtil.toJsonStr(R.fail(ri18nEnum));
        DataBuffer buffer = response.bufferFactory().wrap(responseBody.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer))
                .doOnError(error -> {
                    DataBufferUtils.release(buffer);
                    log.error("Error writing response: {}", error.getMessage());
                });
    }

    public static Mono<Void> writeErrorResponse(ServerHttpResponse response,String message) {
//        HttpStatus status = determineHttpStatus(r);
//        response.setStatusCode(status);
//        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
//        response.getHeaders().setAccessControlAllowOrigin("*");
//        response.getHeaders().setCacheControl("no-cache");

        String responseBody = JSONUtil.toJsonStr(R.fail(message));
        DataBuffer buffer = response.bufferFactory().wrap(responseBody.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer))
                .doOnError(error -> {
                    DataBufferUtils.release(buffer);
                    log.error("Error writing response: {}", error.getMessage());
                });
    }

    private static HttpStatus determineHttpStatus(RI18nEnum ri18nEnum) {
        return switch (ri18nEnum) {
            case ACCESS_UNAUTHORIZED, TOKEN_INVALID -> HttpStatus.UNAUTHORIZED;
            case TOKEN_ACCESS_FORBIDDEN -> HttpStatus.FORBIDDEN;
            default -> HttpStatus.BAD_REQUEST;
        };
    }


}
